package com.dagene.weixin.util;

import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;  

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;

import net.sf.json.JSONObject;

public class SignsUtil {
	
	static long lasttimeAccessToken = 0l;
	static String jsapiTicket = null;
	public static String getJsapiTicket() throws Exception {
		if (System.currentTimeMillis()-lasttimeAccessToken>7200 || jsapiTicket==null) {
			//https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi
			String jsapiTicketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token="
					+  TokenUtil.getAccessToken();
			JSONObject jsonObj = getJSONObjectByGet(jsapiTicketUrl);
			lasttimeAccessToken = System.currentTimeMillis();
			if (jsonObj.has("ticket")) {//判断json是否为空		
				jsapiTicket = jsonObj.get("ticket").toString();
				return jsapiTicket;
			}
			return jsapiTicket;
		} else {
			return jsapiTicket;
		}
	}
	
	//获取签名
    public static void main(String[] args) throws Exception {
        String jsapi_ticket = getJsapiTicket();

        // 注意 URL 一定要动态获取，不能 hardcode
        String url = Constants.NowweixinUrl + "/";
        Map<String, String> ret = sign(jsapi_ticket, url);
        for (Map.Entry entry : ret.entrySet()) {
            System.out.println(entry.getKey() + ", " + entry.getValue());
        }
    }

    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        String string1;
        String signature = "";

        //注意这里参数名必须全部小写，且必须有序
        string1 = "jsapi_ticket=" + jsapi_ticket +
                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);

        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));
            signature = byteToHex(crypt.digest());
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url", url);
        ret.put("jsapi_ticket", jsapi_ticket);
        ret.put("nonceStr", nonce_str);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);

        return ret;
    }

    private static String byteToHex(final byte[] hash) {
        Formatter formatter = new Formatter();
        for (byte b : hash)
        {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }
    
    public static JSONObject getJSONObjectByGet(String requestUrl){
		BufferedReader bufferedReader=null;  
		HttpResponse httpResponse = null;
		JSONObject resultJsonObject=null;
        try {  
            //HttpClient发出一个HttpGet请求  
        	HttpClient httpClient = getHttpClient();
            httpResponse=httpClient.execute(new HttpGet(requestUrl));         
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        //得到httpResponse的状态响应码  
        int statusCode=httpResponse.getStatusLine().getStatusCode();  
        if (statusCode==HttpStatus.SC_OK) {  
            //得到httpResponse的实体数据  
            HttpEntity httpEntity=httpResponse.getEntity();  
            StringBuilder entityStringBuilder=new StringBuilder();
            if (httpEntity!=null) {  
                try {  
                    bufferedReader=new BufferedReader  
                    (new InputStreamReader(httpEntity.getContent(), "UTF-8"), 8*1024);  
                    String line=null;  
                    while ((line=bufferedReader.readLine())!=null) {  
                        entityStringBuilder.append(line);  
                    }  
                    //利用从HttpEntity中得到的String生成JsonObject  
                    resultJsonObject =  JSONObject.fromObject(entityStringBuilder.toString());
                   // resultJsonObject=  new JSONParser().parse(entityStringBuilder.toString()); 
                    
                } catch (Exception e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
        return resultJsonObject;
	}
    
    private static HttpClient getHttpClient(){     
		HttpClient httpClient= HttpClientBuilder.create().build();
        return httpClient;  
    }
}
